﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace J.StatusRepository
{
    public class BaseRepository<T>:IRepository<T> where T : class,new()
    {
        protected readonly MyDbContext context;
        public BaseRepository(MyDbContext context)
        {
            this.context = context;
        }
        public DbSet<T> db => context.Set<T>();
        public async Task<int> AddAsync(T entity)
        {
            await db.AddAsync(entity);
            return await context.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(int id)
        {
            var list = await db.FindAsync(id);
            db.Remove(list);
            return await context.SaveChangesAsync();
        }

        public async Task<int> DeleteRangeAsync(List<T> deleteList)
        {
            db.RemoveRange(deleteList);
            return await context.SaveChangesAsync();
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await db.ToListAsync();
        }

        public async Task<List<T>> GetAllAsync(Expression<Func<T, bool>> expres)
        {
            return await db.Where(expres).ToListAsync();
        }

        public async Task<T> GetModelAsync(int id)
        {
            return await db.FindAsync(id);
        }

        public async Task<int> UpdateAsync(T entity)
        {
            db.Update(entity);
            return await context.SaveChangesAsync();
        }
        public IQueryable<T> query()
        {
            return db.AsQueryable();
        }
    }
}
